package com.kate.mall.product.service.impl;

import com.google.common.collect.Maps;
import com.kate.mall.product.entity.GoodsEntity;
import com.kate.mall.product.entity.GoodsProductEntity;
import com.kate.mall.product.service.GoodsProductService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kate.mall.common.utils.PageUtils;
import com.kate.mall.common.utils.Query;

import com.kate.mall.product.dao.CommentDao;
import com.kate.mall.product.entity.CommentEntity;
import com.kate.mall.product.service.CommentService;

import javax.annotation.Resource;


@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, CommentEntity> implements CommentService {

    @Resource
    private GoodsProductService goodsProductService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CommentEntity> page = this.page(
                new Query<CommentEntity>().getPage(params),
                generatorWrapper(params)
        );

        return new PageUtils(page);
    }
    private  QueryWrapper<CommentEntity> generatorWrapper(Map<String, Object> params){
        QueryWrapper<CommentEntity> goodsEntityQueryWrapper = new QueryWrapper<>();


        if (params.containsKey("goods_id")) {
            //查询该商品的所有货品ID
            Map paraMap = Maps.newHashMap();
            paraMap.put("goods_id", params.get("goods_id"));
            PageUtils pageUtils = goodsProductService.queryPage(paraMap);
            List productIds = new ArrayList<Integer>();
            pageUtils.getList().forEach(e -> {
                if (e instanceof GoodsProductEntity) {
                    GoodsProductEntity goodsProductEntity = (GoodsProductEntity) e;
                    productIds.add(goodsProductEntity.getId());
                }
            });

            //查询所有获评的评论
            if(productIds.size()==0){
                productIds.add(-1);
            }
            goodsEntityQueryWrapper.lambda().in(CommentEntity::getProductId,productIds);
        }
        //查询的商品必须是逻辑上未删除的商品
        //goodsEntityQueryWrapper.lambda().eq(CommentEntity::, 0);
        return goodsEntityQueryWrapper;
    }

}